<?php
/**
 * Feeds manager Component
 *
 * @package		yos_news_crawler
 * @subpackage	CMS
 * @link		http://yopensource.com
 * @author		yopensource
 * @copyright 	yopensource (yopensource@gmail.com)
 * @license		Commercial
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
JTable::addIncludePath(JPATH_COMPONENT_SITE.DS.'cms'.DS.'drupal'.DS.'tables');
class YOS_Cms_Drupal extends JObject {
	//object article
	private $_arr_article;
	
	public $_db		=	null;
	
	//store job id key
	private $_job_configuration;
	
	var $cms_config	=	array();
	
	public function __construct($job_configuration, $arr_article)
	{
		$this->_job_configuration = $job_configuration;
		$this->_arr_article = $arr_article;
		if (!$this->_db	=	$this->getDBO()) {
			return false;
		}
		$this->_get_cmsconfig();	
	}
			
	//when job call store_article function,
	//-store images file
	//-build Joomla article
	//-store in database
	
		function getDBO()
	{
		require(JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.'drupal'.DS.'cms_config.php');		
		$option_ 	= array(); //prevent problems 
		$option_['driver']   = $d_w_driver;       	// Database driver name
		$option_['host']     = $d_w_host;    		// Database host name
		$option_['user']     = $d_w_user;  	    	// User for database authentication
		$option_['password'] = $d_w_password;  		// Password for database authentication
		$option_['database'] = $d_w_database;  	  	// Database name
		$option_['prefix']   = $d_w_prefix;          // Database prefix (may be empty)
		if (empty($option_['user']) || empty($option_['password']) || empty($option_['database']) || empty($option_['driver']) || empty($option_['host']))
		{
			$config	=	JFactory::getConfig();
			
			$option_['driver']   = $config->getValue('dbtype');       	// Database driver name
			$option_['host']     = $config->getValue('host');    		// Database host name
			$option_['user']     = $config->getValue('user');  	    	// User for database authentication
			$option_['password'] = $config->getValue('password');  		// Password for database authentication
			$option_['database'] = $config->getValue('db');  	  	// Database name
		}
		$db_	= &JDatabase::getInstance( $option_ );
		if (!empty($db_->message)) {
				$this->msg = JText::sprintf($db_->message);
				return false;
			}	
		$this->_dbo=$db_;
		return $this->_dbo;
	}
	public function store_articles()
	{
		$db	 =& JFactory::getDBO();
		
		
		$cms_params_file = JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.'drupal'.DS.'cms_config_job.xml';
		if(!is_readable($cms_params_file)){
			$this->setError('[CMS JOOMLA] unable to load params configure file: '.$cms_params_file);
			return false;
		}
		$params = new JParameter($this->_job_configuration->params, $cms_params_file);
		$time_plus = 0;
		
		$db_drupal	=	$this->getDBO();
		$query	=	'SELECT language FROM `#__languages` WHERE enabled=1';
		$db_drupal->setQuery($query);
		$language	=	$db_drupal->loadResult();
			var_dump($language); die();
		foreach ($this->_arr_article as &$article){
			//check article link is exist			
			$query = "SELECT COUNT(*) FROM #__yos_content_link WHERE `link` = ".$db->Quote($article->link)." 
				AND `cms` = 'drupal'";
			$db->setQuery($query);
			$is_exist = $db->loadResult();
			if ($db->getErrorNum()) {
				$arr_error = debug_backtrace();
				$this->setError('[CMS DRUPAL] MySQL error: '.$db->getErrorMsg()."\n FILE: ".$arr_error['file']."\n LINE: ".$arr_error['line']);
				return false;
			}
			if ($is_exist) {
				continue;
			}			
			$row = $this->_store_article($article, $params, $time_plus,$language);			
			
			$time_plus = $time_plus + 10;
			if (!$row) {
				continue;
			}
			$this->_added_fetched_article($article->link, $row);
									
			//store image...
			if ($this->_job_configuration->get_img) {
				if($this->_move_image($article->image_path, $row)){
					//update article
					$dispatcher		= &JDispatcher::getInstance();
					JPluginHelper::importPlugin('content');				
					$result	= $dispatcher->trigger('onBeforeNodeRevisionsSave', array (&$row, false ));
					$row->store();
					$result	= $dispatcher->trigger('onAfterNodeRevisionsSave', array (&$row, false ));
				}		
			}
		}
	}
	
	private function _move_image($image_path, &$row){
		//TODO: get destination image path from cms configure here
		if (count($this->cms_config)==0) {
			$this->_get_cmsconfig();
		}
		$config	=	$this->cms_config;	
		$dest_img_path =$config['image_path_root'].DS.$row->nid;
		$new_img_base_url =$config['image_url_root'].'/'.$row->nid.'/';	
		
		if(!JFolder::create($dest_img_path)){
			$this->setError('[CMS DRUPAL] cannot create folder to store images: '.$dest_img_path);
			return false;
		}
		if (!is_writable($dest_img_path)) {
			$this->setError('[CMS DRUPAL] image path is not writable: '.$dest_img_path);
			return false;
		}		
		$row->teaser = $this->_move_image_in_string($row->teaser, $image_path, $dest_img_path, $new_img_base_url);
		$row->body = $this->_move_image_in_string($row->body, $image_path, $dest_img_path, $new_img_base_url);
		
		return true;
	}
	
	private function _move_image_in_string($str_in, $image_path, $dest_img_path, $new_img_base_url){
		if (!preg_match_all('/<img.*?src="([^"]+)"[^>]*>/ism', $str_in, $matches)) {
			return $str_in;
		}		
		foreach ($matches[1] as $str_img_src){
			$file_name = JFile::getName($str_img_src);
			$file_name = urldecode($file_name);
			if (!is_readable($image_path.DS.$file_name)) {
				continue;
			}
			if(!JFile::copy($image_path.DS.$file_name, $dest_img_path.DS.$file_name)){
				continue;
			}
			$str_in = str_replace($str_img_src, $new_img_base_url.$file_name, $str_in);
		}
		
		return $str_in;
	}
	
	//get cms configuration
	private function _get_cmsconfig()
	{
		if ($this->cms_config) {
			return $this->cms_config;
		}
		$config_file = JPATH_COMPONENT_ADMINISTRATOR.DS.'cms'.DS.'drupal'.DS.'cms_config.php';
		if(!is_readable($config_file)){
			$this->setError('[CMS JOOMLA] unable to load configure file: '.$config_file);
			return false;
		}
		require($config_file);	
		$this->cms_config['image_path_root']	=	$image_path_root;
		$this->cms_config['image_url_root']		=	$image_url_root;
		return $this->cms_config;
	}			
	
	//store an article to database
	private function _store_article(&$obj_article, $params, $time_plus,$language)
	{
		$db	 =& $this->_db;
		
		//add according info
		$str_source_content = $this->_job_configuration->according_to;
		//readmore (add original source link)
		$body	=	"";
		$teaser	=	"";
		$k=0;
		
		if ($obj_article->full_text=="") {
			$k=1;			
			$obj_article->full_text		=	$obj_article->intro_text;	
			
		}
		$obj_article->full_text =$obj_article->full_text."\n".'<p class="according">'.$str_source_content.'</p>';		
		
		//title ads
		if ($this->_job_configuration->title_ext) {
			if ($this->_job_configuration->title_ext_pos == 0) {
				$obj_article->title = $this->_job_configuration->title_ext . $obj_article->title;
			}
			else {
				$obj_article->title = $obj_article->title . $this->_job_configuration->title_ext;
			}			
		}
		
		//intro ads
		if ($this->_job_configuration->ads) {
			if ($this->_job_configuration->catads == 0) {
				$obj_article->intro_text = $this->_job_configuration->ads . $obj_article->intro_text;
			}
			else {
				$obj_article->intro_text = $obj_article->intro_text . $this->_job_configuration->ads;
			}			
		}
		// 
		$body	=	$obj_article->full_text;
		$teaser	=	$obj_article->intro_text;
		if ($k==0) {
			if ($params->get('summary')) {				
				$body 	= 	$obj_article->intro_text.' <!--break--> '. $obj_article->full_text;				
			}
			else {
				$body 	= 	' <!--break--> '. $obj_article->full_text;				
			}
		}		
		
		$time_now		= JFactory::getDate();
		$time_now		= $time_now->toUnix() + $time_plus;//seconds
		
		$row_node = JTable::getInstance('Node','Table');
		$row_node->nid				=	0;
		$row_node->type	 			= 	$params->get('type');
		$row_node->language 		= 	$language;
		$row_node->title 			= 	$obj_article->title;
		$row_node->uid				=	$params->get('author_by');		
		$row_node->status			=	$params->get('published');
		$row_node->created			=	$time_now;
		$row_node->changed			=	$time_now;
		$row_node->comment			=	$params->get('comment_settings');
		$row_node->promote			=	$params->get('front_page');
		$row_node->moderate			=	0;
		$row_node->sticky			=	$params->get('sticky_at');
		$row_node->tnid				=	0;
		$row_node->translate		=	0;
					
		$dispatcher		= &JDispatcher::getInstance();		
		
		JPluginHelper::importPlugin('contentdrupal');
		$result	= $dispatcher->trigger('onBeforeNodeSave', array (&$row_node, true ));
		
		$row_node->store();
		
		if (!$row_node->nid) {
			$this->setError('[CMS DRUPAL] Fail to store node: '.$row_node->getError());
			return false;
		}		
	
		$result	= $dispatcher->trigger('onAfterNodeSave', array (& $row_node, true ));
		
		// store node revisions
		$row_revisions 				=	JTable::getInstance('Node_revisions','Table');
		$row_revisions->nid			=	$row_node->nid;
		$row_revisions->uid			=	$row_node->uid;
		$row_revisions->title		=	$row_node->title;
		$row_revisions->body		=	$body;
		$row_revisions->teaser		=	$teaser;
		$row_revisions->log			=	"";
		$row_revisions->timestamp	=	$time_now;
		$row_revisions->format		=	$params->get('input_format');
		
		$result	= $dispatcher->trigger('onBeforeNodeRevisionsSave', array (&$row_revisions, true ));
		
		$row_revisions->store();		
		if (!$row_revisions->vid) {
			$this->setError('[CMS DRUPAL] Fail to store node revisions: '.$row_revisions->getError());
			return false;
		}		
	
		$result	= $dispatcher->trigger('onAfterNodeRevisionsSave', array (& $row_revisions, true ));
		// update node
		$row_node->vid	=	$row_revisions->vid;
		
		$row_node->store();
		// store node_comment_statistics
		$db	=	$this->_db;
		$query	=	"insert into `#__node_comment_statistics` set
					 nid=$row_node->nid,
					 last_comment_timestamp=$time_now,
					 last_comment_uid=$row_node->uid";
		$db->setQuery($query);
		$db->query();
		if ($db->getErrorNum()) {			
			$this->setError('[CMS DRUPAL] Fail to insert fetched article to list: '.$db->getErrorMsg());
			return false;
		}
		// store node_access
		
		$db	=	$this->_db;
		$query	=	"insert into `#__node_access` set
					 nid=$row_node->nid,
					 gid=0,
					 grant_view=1,
					 grant_update=0,
					 grant_delete=0,
					 realm=".$db->Quote('all');
		$db->setQuery($query);
		$db->query();
		if ($db->getErrorNum()) {			
			$this->setError('[CMS DRUPAL] Fail to insertnode_access: '.$db->getErrorMsg());
			return false;
		}
		// store to term_node
		$term_node	=	$params->get('term');
		$term_node	=	explode(',',$term_node);
		for ($i=0;$i<count($term_node);$i++)
		{
			$query	="INSERT INTO `#__term_node` SET
					 nid=$row_node->nid,
					 vid=$row_revisions->vid,
					 tid=".$term_node[$i];
			$db->setQuery($query);
			$db->query();
			if ($db->getErrorNum()) {			
				$this->setError('[CMS DRUPAL] Fail to insert fetched article to list: '.$db->getErrorMsg());
				return false;
			}
		}
		
		return $row_revisions;
	}			

	// update to yos_content_link
	private function _added_fetched_article($link, $row){
		$db		=&	JFactory::getDBO();
		$query	=	"INSERT INTO #__yos_content_link SET
			`link`	=	".$db->Quote($link).", 
			`title`	=	".$db->Quote($row->title).", 
			`cms`	=	".$db->Quote('drupal').", 
			`articleid`	= $row->nid";
		$db->setQuery($query);
		$db->query();
		
		if ($db->getErrorNum()) {
			$arr_error = debug_backtrace();
			$this->setError('[CMS DRUPAL] Fail to insert fetched article to list: '.$db->getErrorMsg()."\n FILE: ".$arr_error['file']."\n LINE: ".$arr_error['line']);
			return false;
		}
		
		return true;
	}

}